import pandas as pd
import random
import flet as ft
from openpyxl import load_workbook
from openpyxl.styles import Font
import os


# def try_file_path(file_path):
#     """测试是否存在文件，如果存在，返回带括号的文件名"""
#     tmp_path = file_path
#     (root, ext) = os.path.splitext(file_path)
#     i = 1
#     while os.path.exists(tmp_path):
#         tmp_path = f"{root}({i}){ext}"
#         i += 1

#     return tmp_path


def lottery_draw(input_file, output_file, page):
    try:
        # 读取Excel文件
        df = pd.read_excel(input_file)

        # 检查必要的列是否存在
        required_columns = ["班级", "性别"]
        for col in required_columns:
            if col not in df.columns:
                snack_bar = ft.SnackBar(ft.Text(f"错误: 文件中缺少必要的列 '{col}'"))
                page.open(snack_bar)
                page.update()
                return False

        # 获取所有班级列表
        classes = df["班级"].unique()

        # 存储抽奖结果
        results = []

        # 对每个班级进行抽奖
        for class_name in classes:
            # 筛选当前班级的数据
            class_df = df[df["班级"] == class_name]

            # 筛选男生和女生
            male_students = class_df[class_df["性别"] == "男"]
            female_students = class_df[class_df["性别"] == "女"]

            # 随机抽取一男一女
            try:
                selected_male = male_students.sample(1).iloc[0].to_dict()
                selected_female = female_students.sample(1).iloc[0].to_dict()
            except Exception as e:
                snack_bar = ft.SnackBar(
                    ft.Text(f"班级 {class_name} 缺少男生或女生，跳过该班级")
                )
                page.open(snack_bar)
                page.update()
                continue

            # # 添加班级信息
            # selected_male["抽奖结果"] = f"{class_name}班-男生"
            # selected_female["抽奖结果"] = f"{class_name}班-女生"

            # 添加到结果列表
            results.append(selected_male)
            results.append(selected_female)

        # 将结果转换为DataFrame
        result_df = pd.DataFrame(results)

        # 保存结果到Excel文件
        with pd.ExcelWriter(output_file, engine="openpyxl") as writer:
            result_df.to_excel(writer, index=False, sheet_name="抽奖结果")

            # 获取工作簿和工作表对象用于样式设置
            workbook = writer.book
            worksheet = writer.sheets["抽奖结果"]

            # 设置标题行字体加粗
            bold_font = Font(bold=True)
            for cell in worksheet[1]:
                cell.font = bold_font

            # 自动调整列宽
            for column in worksheet.columns:
                max_length = 0
                column_letter = column[0].column_letter
                for cell in column:
                    try:
                        if len(str(cell.value)) > max_length:
                            max_length = len(str(cell.value))
                    except:
                        pass
                adjusted_width = (max_length + 2) * 1.2
                worksheet.column_dimensions[column_letter].width = adjusted_width

        return True

    except Exception as e:
        snack_bar = ft.SnackBar(ft.Text(f"发生错误: {str(e)}"))
        page.open(snack_bar)
        page.update()
        return False


def main(page: ft.Page):
    # 页面设置
    page.title = "班级抽奖系统"
    page.window_width = 500
    page.window_height = 800
    page.vertical_alignment = ft.MainAxisAlignment.CENTER
    page.horizontal_alignment = ft.CrossAxisAlignment.CENTER

    # 文件选择器
    def pick_files_result(e: ft.FilePickerResultEvent):
        if e.files:
            selected_file.value = e.files[0].path
            selected_file.update()

    file_picker = ft.FilePicker(on_result=pick_files_result)
    page.overlay.append(file_picker)

    selected_file = ft.Text("未选择文件", size=16)
    output_file = ft.TextField(label="输出文件名", value="抽奖结果.xlsx", width=400)

    # 抽奖结果展示
    result_display = ft.Column(scroll=ft.ScrollMode.ALWAYS, height=400)

    # 执行抽奖
    def start_lottery(e):
        if not selected_file.value or selected_file.value == "未选择文件":
            snack_bar = ft.SnackBar(ft.Text("请先选择输入文件"))
            page.open(snack_bar)
            page.update()
            return

        if not output_file.value:
            snack_bar = ft.SnackBar(ft.Text("请指定输出文件名"))
            page.open(snack_bar)
            page.update()
            return

        # 显示加载中
        progress_ring.visible = True
        start_btn.disabled = True
        page.update()

        # 执行抽奖
        success = lottery_draw(selected_file.value, output_file.value, page)

        # 隐藏加载中
        progress_ring.visible = False
        start_btn.disabled = False

        if success:

            # 显示结果
            result_df = pd.read_excel(output_file.value)
            result_rows = []

            # 添加表头
            columns = result_df.columns.tolist()
            header_cells = [
                ft.DataCell(ft.Text(col, weight=ft.FontWeight.BOLD)) for col in columns
            ]
            # result_rows.append(ft.DataRow(cells=header_cells))

            # 添加数据行
            for _, row in result_df.iterrows():
                cells = [ft.DataCell(ft.Text(str(row[col]))) for col in columns]
                result_rows.append(ft.DataRow(cells=cells))

            result_display.controls = [
                ft.Text("抽奖结果:", size=18, weight=ft.FontWeight.BOLD),
                ft.DataTable(
                    columns=[ft.DataColumn(ft.Text(col)) for col in columns],
                    rows=result_rows,
                    border=ft.border.all(1, ft.Colors.GREY_400),
                    border_radius=10,
                    horizontal_margin=10,
                    column_spacing=20,
                    width=500,
                ),
            ]

            snack_bar = ft.SnackBar(
                ft.Text(f"抽奖完成！结果已保存到 {output_file.value}")
            )
            page.open(snack_bar)

        page.update()

    # 界面组件
    progress_ring = ft.ProgressRing(visible=False)
    start_btn = ft.ElevatedButton(
        "开始抽奖", icon=ft.Icons.PLAY_ARROW, on_click=start_lottery, width=200
    )

    page.add(
        ft.Column(
            [
                ft.Text("班级抽奖系统", size=24, weight=ft.FontWeight.BOLD),
                ft.Text("每班男女各随机抽出一人", size=18, weight=ft.FontWeight.NORMAL),
                ft.Divider(),
                ft.Row(
                    [
                        ft.Column(
                            [
                                ft.ElevatedButton(
                                    "选择Excel文件",
                                    icon=ft.Icons.UPLOAD_FILE,
                                    on_click=lambda _: file_picker.pick_files(
                                        allowed_extensions=["xlsx"],
                                        dialog_title="选择学生名单Excel文件",
                                    ),
                                ),
                                selected_file,
                                ft.Row(
                                    [progress_ring, start_btn],
                                    alignment=ft.MainAxisAlignment.START,
                                ),
                            ],
                            alignment=ft.MainAxisAlignment.START,
                            width=400,
                        ),
                        ft.Column(
                            [
                                output_file,
                                result_display,
                            ]
                        ),
                    ],
                    vertical_alignment=ft.CrossAxisAlignment.START,
                    spacing=20,
                ),
            ],
            spacing=20,
        )
    )


if __name__ == "__main__":
    ft.app(target=main)
